/**
 * 积分商城-今日任务
 */
'use strict';
import React, {
    Component
} from 'react'
import {
    Link
} from 'react-router'

import Header from './Common/Header'
import {
    HttpService,
    getLocalTime,
    Tips
} from '../Tools'

import '../Plugins/swiper/css/swiper.css'
import '../Plugins/swiper/js/swiper.jquery.min.js'

import imgbusiness from '../Img/mall/integral/business.png'
import imgErr from '../Img/other/splitGraphBig.png'
import imgErr2 from '../Img/other/splitImg.jpg'
import star from '../Img/mall/integral/star.png'
import star2 from '../Img/mall/integral/star2.png'
import star3 from '../Img/mall/integral/star3.png'

export default class companyInfo extends Component {
    constructor(props) {
        super(props);
        this.state = {
            data: {},
            dataList: [],
            moreCompany: []
        }
    }

    componentWillMount() {
        this.getDetail()
    }
    componentWillReceiveProps() {
        console.log('reload');
        location.reload();
    }
    componentWillUnmount() {
        $(document).unbind();
        clearTimeout(this.scroll)
    }
    componentDidMount() {
        this.top = $('.cinftab').offset().top - $('.header').height()
        let addHeight = $('.cinftab').height()
        $(document).scroll(function() {
            const bottom = $(document).height() - $(window).height() - $(window).scrollTop()
            if ($(document).scrollTop() > this.top) {
                $('.cinftab').addClass('cinftabfixed')
                $('.cifngoodlist').css('paddingTop', addHeight)

                let index = 0
                if (bottom < $('.cinfointegral').height()) {
                    index = 1
                    if (bottom < 10)
                        index = 2
                }
                if (this.scroll)
                    return
                $('.cinftab li').eq(index).addClass('active').siblings().removeClass('active');
            } else {
                $('.cinftab').removeClass('cinftabfixed')
                $('.cifngoodlist').css('paddingTop', 0)
                if (this.scroll)
                    return
                if (bottom > this.top || this.state.dataList.length > 3)
                    $('.cinftab li:first').addClass('active').siblings().removeClass('active');
            }
        }.bind(this))
    }

    //切换效果
    tabSwitch(e) {
        if ($(e.currentTarget).hasClass('active'))
            return
        $(e.currentTarget).addClass('active').siblings().removeClass('active')
        let index = $(e.currentTarget).index()
        let top = $(document).height() - $(window).height()
        let tabHeight = $('.cinftab').height()
        let signHeight = 120
        if (index != 2 && top < this.top + 1)
            return
        console.log(index);
        if (index == 1) {
            if (top < this.top + tabHeight + signHeight + 1) {
                top -= signHeight + tabHeight + 1
            } else {
                top -= signHeight + 1
            }
        }
        if (index == 0) {
            if (top < this.top + tabHeight + signHeight + 1) {
                top -= signHeight + tabHeight + 1
            } else {
                top = this.top + tabHeight + 1
            }
        }
        this.scroll = true;
        clearTimeout(this.scroll)
        setTimeout(() => {
            this.scroll = false;
        }, 100)
        $(document).scrollTop(top);
    }

    //图片地址错误
    imgErr(src, e) {
        e.currentTarget.setAttribute('src', src)
    }

    //获取详情
    getDetail() {
        HttpService.query({
            // url: '/src/data/integral/companyInfo.json',
            url: '/jf/company/get',
            async: false,
            data: {
                token: sessionStorage.appToken,
                companyId: this.props.params.id
            },
            success: (res => {
                if (res.code == 10140 && res.data) {
                    this.setState({
                        data: res.data
                    })
                    this.getData()
                }
            })
        })
    }

    //获取商家商品
    getData() {
        this.dataLoad = 1
        let data = {
            token: sessionStorage.appToken,
            companyId: this.props.params.id,
            page: 1,
            size: 10,
            range: sessionStorage.userrole == '家长' ? 2 : 1
        };
        if (sessionStorage.userrole == '家长' && sessionStorage.babyid)
            data.babyid = sessionStorage.babyid
        HttpService.query({
            url: '/jf/goodsArchives/pageJfGoodsArchives',
            data,
            success: (res => {
                this.getMoreCompany()
                this.dataLoad = 0
                this.setState({
                    dataLoad: 0
                });
                if (res.code == 10140) {
                    //获取数据成功
                    let dataList = res.data.list
                    if (status != 1)
                        dataList = this.state.dataList.concat(res.data.list);
                    this.setState({
                        dataList
                    });
                    if (res.data.total == this.pagesize) {
                        this.setState({
                            dataEnd: 1
                        });
                    } else if (res.data.list.length < this.pagesize) {
                        this.setState({
                            dataEnd: 1
                        });
                        if (dataList.length == 0) {
                            this.setState({
                                dataEnd: 0,
                                dataNull: 1
                            });
                        }
                    }
                    return;
                }
                this.setState({
                    dataEnd: 1
                });
            })
        })
    }

    //更多优惠-商家展示
    getMoreCompany() {
        let data = {
            token: sessionStorage.appToken,
            page: 1,
            size: 6,
            range: sessionStorage.userrole == '家长' ? 2 : 1
        };
        if (sessionStorage.userrole == '家长' && sessionStorage.babyid)
            data.babyid = sessionStorage.babyid
        HttpService.query({
            url: '/jf/company/pageJfCompanyArchOnly',
            data,
            success: (res => {
                if (res.code == 10140) {
                    this.setState({
                        moreCompany: res.data.list
                    });
                    //swiper
                    var swiper = new Swiper('.swiper-container', {
                        slidesPerView: 3.7,
                        spaceBetween: 24,
                        freeMode: true,
                        pagination: {
                            // el: '.swiper-pagination',
                            clickable: true,
                        },
                    });
                }
            })
        })
    }

    //评价匹配
    getStar(num) {
        const htmlstar = `<img src=${star} />`,
            htmlstar2 = `<img src=${star2} />`,
            htmlstar3 = `<img src=${star3} />`;
        let html = ''
        for (let i = 0; i < num; i++) {
            html += htmlstar;
        }
        for (let i = 0; i < (5 - num); i++) {
            html += htmlstar3;
        }
        return html
    }

    render() {
        const {
            detalHtml,
            dataList,
            moreCompany,
            data
        } = this.state
        let {
            id,
            name,
            companyImgs,
            logo,
            level,
            address,
            intentArea,
            linkPhone,
            businessType,
            introduce
        } = data
        introduce = decodeURIComponent(introduce)

        let unit = sessionStorage.userrole == '家长' ? '积分' : '荣誉值';
        const goodsTag = dataList.map(item => {
            let url = imgErr,
                sign;
            if (item.smallImg.indexOf('{') > -1)
                url = JSON.parse(item.smallImg).goodsHeaderImg
            if (item.cardProperty == 1)
                sign = 'type'
            if (item.cardProperty == 2)
                sign = 'type quan'
            return (
                <li>
                    <Link to={"/ProductDetails/"+item.id} className="product_info">
                        <span className={sign} />
                        <img className="img" src={url} />
                        <div className="name">{item.name}</div>
                        <div className="punkte">{unit}:<span>{item.consumeCredit}</span></div>
                    </Link>
                </li>
            )
        })
        const moreCompanyTag = moreCompany.map(item => {
            return (
                <li className="swiper-slide">
                    <Link className='item' to={`/companyInfo/${item.id}`}>
                        <img src={item.logo} onError={this.imgErr.bind(this,imgErr2)} />
                        <p>{item.name}</p>
                    </Link>
                </li>
            )
        })
        return (
            <div className="packagedetails cpyintro">
                <Header title="商家详情" />
                <Link className="cinfotop bgc-white">
                    <div className='img'><img src={companyImgs?companyImgs:imgErr} onError={this.imgErr.bind(this,imgErr)} /></div>
                    <div className="others">
                        <h5>{name}</h5>
                        <p className='intentArea'>{address.split('-')[1]} {address.split('-')[2]}</p>
                        <p className='star' dangerouslySetInnerHTML={{__html: this.getStar(level)}} />
                    </div>
                </Link>
                <div className='adtelstr bgc-white'>
                    <Link className='add' to={`/position/`+encodeURIComponent(escape(name))+`/${encodeURIComponent(escape(address.split('-')[3]))}/${address.split('-')[4]}/${address.split('-')[5]}`}>
                        {address.split('-').map((item,index)=>{
                            if(index<4)
                            return item
                        }) }
                    </Link>
                    <a className='tel' href={`tel:${linkPhone}`} />
                </div>
                <ul className='cinftab bgc-white'>
                    <li onClick={this.tabSwitch.bind(this)} className='active'><span>优惠信息</span></li>
                    <li onClick={this.tabSwitch.bind(this)}><span>商家介绍</span></li>
                    <li onClick={this.tabSwitch.bind(this)}><span>更多优惠</span></li>
                </ul>
                {name?
                <div>
                    <ul className='clearfix cifngoodlist'>
                        {goodsTag}
                    </ul>
                    <Link className='cinfomorebar' to={`/companyDetail/${id}`}>
                        <img src={imgbusiness} />
                        <title>商家介绍</title>
                        <p>{introduce.replace(/<[^>]*>|<\/[^>]*>/gm,'')}</p>
                    </Link>
                    {moreCompany.length>0?<div className='cinfointegral'>
                        <div className='bar'>
                            <span>更多优惠</span>
                        </div>
                        <div className="swiper-container morecompany">
                            <ul className='clearfix swiper-wrapper'>
                                {moreCompanyTag}
                            </ul>
                        </div>
                    </div>:null}
                </div>:<div className="datastatus"><span className="no">无商家信息</span></div>
                }
            </div>
        )
    }
}
